package com.tnxst.phexamination.fragment.follow;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProviders;

import com.bigkoo.pickerview.TimePickerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.tnxst.phexamination.R;
import com.tnxst.phexamination.constant.HISConfig;
import com.tnxst.phexamination.databinding.DoorRecordFirstPhthisisBinding;
import com.tnxst.phexamination.dto.InhabitantDTO;
import com.tnxst.phexamination.dto.TbFirstFollowDTO;
import com.tnxst.phexamination.dto.TbPatientDTO;
import com.tnxst.phexamination.public_health_docking_interface.TuberculosisInterface;
import com.tnxst.phexamination.utils.GsonUtils;
import com.tnxst.phexamination.utils.PictureFileUtil;
import com.tnxst.phexamination.utils.ReflectUtils;
import com.tnxst.phexamination.utils.StringUtils;
import com.tnxst.phexamination.utils.Utils;
import com.tnxst.phexamination.utils.WebServiceUtils;
import com.tnxst.phexamination.viewmodel.GlobalViewModel;

import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;

public class FirstPhthisisFragment extends Fragment implements CompoundButton.OnCheckedChangeListener {
    private GlobalViewModel viewModel;

    private Context context;

    private DoorRecordFirstPhthisisBinding binding;

    private TbFirstFollowDTO tbFirstFollowDTO;

    private InhabitantDTO inhabitantDTO;

    private List<Map<String,Object>> otherJson;

    private boolean flag = false;

    private TbPatientDTO tbPatientDTO;

    //新增定位功能及拍照功能的控件
    private EditText address;

    private ImageView picture1;

    private ImageView picture2;

    private ImageView picture3;

    private Switch aSwitch;

    private Button start;

    private TextView del1;

    private TextView del2;

    private TextView del3;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        binding = DataBindingUtil.inflate(inflater, R.layout.door_record_first_phthisis, container, false);
        context = container.getContext();
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewModel = ViewModelProviders.of(requireActivity()).get(GlobalViewModel.class);
        initData();
        initView();
        initAddress();
    }

    /**
     * 初始化视图
     */
    private void initView() {
        //病人信息
        binding.editText2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String idCard = s.toString();
                if (idCard.length() >= 2 ){
                    List<InhabitantDTO> dtoList = viewModel.getInhabitantRepository().findByFieldList("NAME", idCard);
                    if (!CollectionUtils.isEmpty(dtoList)){
                        InhabitantDTO i = dtoList.get(0);
                        if (i != null){
                            inhabitantDTO = i;
//                            if (StringUtils.isNotNull(HISConfig.PRODUCT_CODE)){
//                                TuberculosisInterface.verifyIsTbPatient(inhabitantDTO.getID(), new WebServiceUtils.Response<Map>() {
//                                    @Override
//                                    public void onSuccess(Map result) {
//                                        String is = result.get("Msg").toString();
//                                        if ("1.0".equals(is)){
//                                            return;
//                                        }
//                                    }
//                                    @Override
//                                    public void onError(String error) {
//                                        Utils.Toast(context,"验证患者是否失败！\n失败原因：" + error);
//                                    }
//                                });
//                            }
                            setInhabitantView();
                        }else {
                            clearInhabitantView();
                        }
                    }else {
                        clearInhabitantView();
                        inhabitantDTO = null;
                    }
                }
            }
        });

        if (StringUtils.isNull(binding.textView256.getText().toString()))
            binding.textView256.setText(Utils.getTime(new Date()));
        binding.textView256.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        binding.textView256.setText(Utils.getTime(date));
                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .setTitleText("取药时间")
                        .setTitleColor(Color.WHITE)//标题文字颜色
                        .setSubmitColor(Color.parseColor("#43c489"))
                        .setCancelColor(Color.parseColor("#43c489"))
                        .setTitleBgColor(Color.parseColor("#43c489"))
                        .setDividerColor(Color.parseColor("#43c489"))
                        .setTextColorCenter(Color.parseColor("#43c489"))
                        .setTitleSize(14)
                        .setContentSize(14)
                        .setSubCalSize(14)
                        .build();

                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
            }
        });

        if (StringUtils.isNull(binding.textView229.getText().toString()))
            binding.textView229.setText(Utils.getTime(new Date()));
        binding.textView229.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        binding.textView229.setText(Utils.getTime(date));
                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .setTitleText("随访时间")
                        .setTitleColor(Color.WHITE)//标题文字颜色
                        .setSubmitColor(Color.parseColor("#43c489"))
                        .setCancelColor(Color.parseColor("#43c489"))
                        .setTitleBgColor(Color.parseColor("#43c489"))
                        .setDividerColor(Color.parseColor("#43c489"))
                        .setTextColorCenter(Color.parseColor("#43c489"))
                        .setTitleSize(14)
                        .setContentSize(14)
                        .setSubCalSize(14)
                        .build();

                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
            }
        });

        if (StringUtils.isNull(binding.textView231.getText().toString()))
            binding.textView231.setText(Utils.getTime(new Date()));
        binding.textView231.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        binding.textView231.setText(Utils.getTime(date));
                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .setTitleText("下次随访时间")
                        .setTitleColor(Color.WHITE)//标题文字颜色
                        .setSubmitColor(Color.parseColor("#43c489"))
                        .setCancelColor(Color.parseColor("#43c489"))
                        .setTitleBgColor(Color.parseColor("#43c489"))
                        .setDividerColor(Color.parseColor("#43c489"))
                        .setTextColorCenter(Color.parseColor("#43c489"))
                        .setTitleSize(14)
                        .setContentSize(14)
                        .setSubCalSize(14)
                        .build();

                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
            }
        });

        binding.button7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideAddFragment();
            }
        });

        binding.button8.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tbFirstFollowDTO.setAddress(address.getText().toString());
                if (StringUtils.isNull(tbFirstFollowDTO.getAddress())
                        || (StringUtils.isNull(tbFirstFollowDTO.getPicturePath1())
                        && StringUtils.isNull(tbFirstFollowDTO.getPicturePath2())
                        && StringUtils.isNull(tbFirstFollowDTO.getPicturePath3()))){
                    Utils.Toast(context,"请完善地址信息或者拍摄现场图片后再保存！");
                    return;
                }
                if (inhabitantDTO == null){
                    Utils.Toast(context,"请完善病人信息！");
                    return;
                }
                tbFirstFollowDTO.setUpload(false);
                tbFirstFollowDTO.setPatientId(inhabitantDTO.getID());
                tbFirstFollowDTO.setPatientName(inhabitantDTO.getNAME());
                save();
                if (StringUtils.isNull(tbFirstFollowDTO.getID()))
                    tbFirstFollowDTO.setID(UUID.randomUUID().toString());
                viewModel.getTbFirstFollowRepository().insert(tbFirstFollowDTO);
                Utils.Toast(context,"保存本地成功！");
                hideAddFragment();
//

            }
        });


        binding.radioButton27.setOnCheckedChangeListener(this);
        binding.radioButton28.setOnCheckedChangeListener(this);
        binding.radioButton29.setOnCheckedChangeListener(this);
        binding.radioButton32.setOnCheckedChangeListener(this);
        binding.radioButton33.setOnCheckedChangeListener(this);
        binding.radioButton34.setOnCheckedChangeListener(this);
        binding.radioButton35.setOnCheckedChangeListener(this);
        binding.radioButton36.setOnCheckedChangeListener(this);
        binding.radioButton37.setOnCheckedChangeListener(this);
        binding.radioButton38.setOnCheckedChangeListener(this);


    }

    private void initAddress() {
        address = binding.include.findViewById(R.id.editTextTextPersonName33);
        picture1 = binding.include.findViewById(R.id.image1);
        picture2 = binding.include.findViewById(R.id.image2);
        picture3 = binding.include.findViewById(R.id.image3);
        aSwitch = binding.include.findViewById(R.id.isFinish);
        start = binding.include.findViewById(R.id.button22);
        del1 = binding.include.findViewById(R.id.text1);
        del2 = binding.include.findViewById(R.id.text2);
        del3 = binding.include.findViewById(R.id.text3);
        viewModel.getAddressUtils().getAddress(address, getActivity());
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PictureFileUtil.showAlbum(FirstPhthisisFragment.this, PictureConfig.CHOOSE_REQUEST);
            }
        });
        del1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tbFirstFollowDTO.setPicturePath1("");
                Utils.loadChatImage(getActivity(),getResources().getDrawable(R.drawable.no_image), picture1);
            }
        });
        del2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tbFirstFollowDTO.setPicturePath2("");
                Utils.loadChatImage(getActivity(),getResources().getDrawable(R.drawable.no_image), picture2);
            }
        });
        del3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tbFirstFollowDTO.setPicturePath3("");
                Utils.loadChatImage(getActivity(),getResources().getDrawable(R.drawable.no_image), picture3);
            }
        });

        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b)
                    tbFirstFollowDTO.setIsFinish(1);
                else
                    tbFirstFollowDTO.setIsFinish(0);
            }
        });

        if (StringUtils.isNotNull(tbFirstFollowDTO.getPicturePath1()))
            Utils.loadChatImage(getActivity(),tbFirstFollowDTO.getPicturePath1(), picture1);
        if (StringUtils.isNotNull(tbFirstFollowDTO.getPicturePath2()))
            Utils.loadChatImage(getActivity(),tbFirstFollowDTO.getPicturePath2(), picture2);
        if (StringUtils.isNotNull(tbFirstFollowDTO.getPicturePath3()))
            Utils.loadChatImage(getActivity(),tbFirstFollowDTO.getPicturePath3(), picture3);
        if (StringUtils.isNotNull(tbFirstFollowDTO.getAddress())){
            address.setText(tbFirstFollowDTO.getAddress());
        } else{
            viewModel.getAddressUtils().getAddress(address, getActivity());
        }

        if (tbFirstFollowDTO.getIsFinish() == 0)
            aSwitch.setChecked(false);
        else
            aSwitch.setChecked(true);

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            // 图片选择结果回调
            tbFirstFollowDTO.setPicturePath1("");
            tbFirstFollowDTO.setPicturePath2("");
            tbFirstFollowDTO.setPicturePath3("");
            Utils.loadChatImage(getActivity(),getResources().getDrawable(R.drawable.no_image), picture1);
            Utils.loadChatImage(getActivity(),getResources().getDrawable(R.drawable.no_image), picture2);
            Utils.loadChatImage(getActivity(),getResources().getDrawable(R.drawable.no_image), picture3);

            List<LocalMedia> selectListPic = PictureSelector.obtainMultipleResult(data);
            tbFirstFollowDTO.setPicturePath1(selectListPic.size() > 0 ? selectListPic.get(0).getRealPath() : "");
            tbFirstFollowDTO.setPicturePath2(selectListPic.size() > 1 ? selectListPic.get(1).getRealPath() : "");
            tbFirstFollowDTO.setPicturePath3(selectListPic.size() > 2 ? selectListPic.get(2).getRealPath() : "");
            Utils.loadChatImage(getActivity(),tbFirstFollowDTO.getPicturePath1(), picture1);
            Utils.loadChatImage(getActivity(),tbFirstFollowDTO.getPicturePath2(), picture2);
            Utils.loadChatImage(getActivity(),tbFirstFollowDTO.getPicturePath3(), picture3);
        }
    }

    /**
     * 保存数据
     */
    private void save(){
        //服药后不良反应及处理
        int checkedRadioButtonId = binding.radioGroupPlus015.getCheckedRadioButtonId();
        String adverseDrugReactions = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton82:
                adverseDrugReactions = "1";
                break;
            case R.id.radioButton83:
                adverseDrugReactions = "2";
                break;
        }
        tbFirstFollowDTO.setAdverseDrugReactions(adverseDrugReactions);

        //单独的居室(1 有，2 无)
        checkedRadioButtonId = binding.radioGroupPlus09.getCheckedRadioButtonId();
        String alongBedroom = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton69:
                alongBedroom = "1";
                break;
            case R.id.radioButton70:
                alongBedroom = "2";
                break;
        }
        tbFirstFollowDTO.setAlongBedroom(alongBedroom);

        //通风情况(1 良好，2 一般，4 差)
        checkedRadioButtonId = binding.radioGroupPlus010.getCheckedRadioButtonId();
        String areationType = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton71:
                areationType = "1";
                break;
            case R.id.radioButton72:
                areationType = "2";
                break;
            case R.id.radioButton73:
                areationType = "4";
                break;
        }
        tbFirstFollowDTO.setAreationType(areationType);

        //密切接触者检查
        checkedRadioButtonId = binding.radioGroupPlus019.getCheckedRadioButtonId();
        String contactsExam = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton90:
                contactsExam = "1";
                break;
            case R.id.radioButton91:
                contactsExam = "2";
                break;
        }
        tbFirstFollowDTO.setContactsExam(contactsExam);

        //医生信息
        tbFirstFollowDTO.setDoctorID(viewModel.getUserInfo().getDId());
        tbFirstFollowDTO.setDoctorName(viewModel.getUserInfo().getDoctorName());

        //服药记录卡的填写
        checkedRadioButtonId = binding.radioGroupPlus011.getCheckedRadioButtonId();
        String drugCardFill = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton74:
                drugCardFill = "1";
                break;
            case R.id.radioButton75:
                drugCardFill = "2";
                break;
        }
        tbFirstFollowDTO.setDrugCardFill(drugCardFill);

        //服药方法及药品存放
        checkedRadioButtonId = binding.radioGroupPlus012.getCheckedRadioButtonId();
        String drugCardStore = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton76:
                drugCardStore = "1";
                break;
            case R.id.radioButton77:
                drugCardStore = "2";
                break;
        }
        tbFirstFollowDTO.setDrugCardStore(drugCardStore);

        //耐药情况(1 耐药，2 非耐药，4未检测)
        checkedRadioButtonId = binding.radioGroupPlus04.getCheckedRadioButtonId();
        String drugFastType = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton56:
                drugFastType = "1";
                break;
            case R.id.radioButton57:
                drugFastType = "2";
                break;
            case R.id.radioButton58:
                drugFastType = "4";
                break;
        }
        tbFirstFollowDTO.setDrugFastType(drugFastType);

        //不规律服药危害
        checkedRadioButtonId = binding.radioGroupPlus014.getCheckedRadioButtonId();
        String drugHarm = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton80:
                drugHarm = "1";
                break;
            case R.id.radioButton81:
                drugHarm = "2";
                break;
        }
        tbFirstFollowDTO.setDrugHarm(drugHarm);

        //随访时间
        tbFirstFollowDTO.setFollowUpDate(binding.textView229.getText().toString());

        //生活习惯及注意事项
        checkedRadioButtonId = binding.radioGroupPlus018.getCheckedRadioButtonId();
        String livingPrecautions = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton88:
                livingPrecautions = "1";
                break;
            case R.id.radioButton89:
                livingPrecautions = "2";
                break;
        }
        tbFirstFollowDTO.setLivingPrecautions(livingPrecautions);

        //下次目标饮酒量
        tbFirstFollowDTO.setNextDailyAlcohol(binding.editTextTextPersonName6.getText().toString());

        //下次随访时间
        tbFirstFollowDTO.setNextFollowUpDate(binding.textView231.getText().toString());

        //下次目标吸烟量
        tbFirstFollowDTO.setNextSmoking(binding.editTextTextPersonName5.getText().toString());

        //外出期间如何坚持服药
        checkedRadioButtonId = binding.radioGroupPlus017.getCheckedRadioButtonId();
        String outdoorMedication = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton86:
                outdoorMedication = "1";
                break;
            case R.id.radioButton87:
                outdoorMedication = "2";
                break;
        }
        tbFirstFollowDTO.setOutdoorMedication(outdoorMedication);

        //患者类型(1 初治，2 复治)
        checkedRadioButtonId = binding.radioGroupPlus02.getCheckedRadioButtonId();
        String patientType = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton51:
                patientType = "1";
                break;
            case R.id.radioButton52:
                patientType = "2";
                break;
        }
        tbFirstFollowDTO.setPatientType(patientType);

        //取药时间
        tbFirstFollowDTO.setPecipeDate(binding.textView256.getText().toString());

        //取药地点
        tbFirstFollowDTO.setRecipePlace(binding.editTextTextPersonName7.getText().toString());

        //痰菌情况(1 阳性，2 阴性，4 未查痰)
        checkedRadioButtonId = binding.radioGroupPlus03.getCheckedRadioButtonId();
        String sputumType = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton53:
                sputumType = "1";
                break;
            case R.id.radioButton54:
                sputumType = "2";
                break;
            case R.id.radioButton55:
                sputumType = "4";
                break;
        }
        tbFirstFollowDTO.setSputumType(sputumType);

        //督导人员选择(1 医生，2 家属，4 自服药，8 其他)
        checkedRadioButtonId = binding.radioGroupPlus08.getCheckedRadioButtonId();
        String supervisor = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton65:
                supervisor = "1";
                break;
            case R.id.radioButton66:
                supervisor = "2";
                break;
            case R.id.radioButton67:
                supervisor = "4";
                break;
            case R.id.radioButton68:
                supervisor = "8";
                break;
        }
        tbFirstFollowDTO.setSupervisor(supervisor);

        //症状(1 没有症状，2 咳嗽咳痰，4 低热盗汗，8 咯血或血痰，16 胸痛消瘦，32 恶心纳差，64 头痛失眠，128 视物模糊，256 皮肤瘙痒、皮疹，512 耳鸣、听力下降，1024 其他)
        tbFirstFollowDTO.setSymptom(totalSymptom());

        //结核病基本信息ID

        //肺结核治疗疗程
        checkedRadioButtonId = binding.radioGroupPlus013.getCheckedRadioButtonId();
        String tbTreatment = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton78:
                tbTreatment = "1";
                break;
            case R.id.radioButton79:
                tbTreatment = "2";
                break;
        }
        tbFirstFollowDTO.setTbTreatment(tbTreatment);

        //治疗期间复诊查痰
        checkedRadioButtonId = binding.radioGroupPlus016.getCheckedRadioButtonId();
        String treatementSputum = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton84:
                treatementSputum = "1";
                break;
            case R.id.radioButton85:
                treatementSputum = "2";
                break;
        }
        tbFirstFollowDTO.setTreatementSputum(treatementSputum);

        //随访方式(1 门诊，2 家庭)
        checkedRadioButtonId = binding.radioGroupPlus01.getCheckedRadioButtonId();
        String wayUp = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton50:
                wayUp = "1";
                break;
            case R.id.radioButton49:
                wayUp = "2";
                break;
        }
        tbFirstFollowDTO.setWayUp(wayUp);

        //化疗方案
        tbFirstFollowDTO.setChemotherapyRegimen(binding.editTextTextPersonName4.getText().toString());

        //药品剂型(1 固定剂量复合制剂，2 散装药，4 板式组合，8注射剂)
        int dosage = 0;
        if (binding.radioButton61.isChecked())
            dosage+=1;
        if (binding.radioButton62.isChecked())
            dosage+=2;
        if (binding.radioButton63.isChecked())
            dosage+=4;
        if (binding.radioButton64.isChecked())
            dosage+=8;

        tbFirstFollowDTO.setDosage(String.valueOf(dosage));

        //用法(1 每日，2 间歇)
        checkedRadioButtonId = binding.radioGroupPlus06.getCheckedRadioButtonId();
        String usage = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton59:
                usage = "1";
                break;
            case R.id.radioButton60:
                usage = "2";
                break;
        }
        tbFirstFollowDTO.setUsage(usage);

        //日饮酒量
        tbFirstFollowDTO.setDailyAlcoholIntake(binding.editTextTextPersonName6.getText().toString());

        //日吸烟量
        tbFirstFollowDTO.setSmoking(binding.editTextTextPersonName5.getText().toString());

        //otherJson
        tbFirstFollowDTO.setOtherJson(GsonUtils.toJson(otherJson));
    }

    /**
     * 计算症状总值
     * @return
     */
    private String totalSymptom() {
        int symptom = 0;
        if (binding.radioButton27.isChecked())
            return "1";
        if (binding.radioButton28.isChecked())
            symptom+=2;
        if (binding.radioButton29.isChecked())
            symptom+=4;
        if (binding.radioButton32.isChecked())
            symptom+=8;
        if (binding.radioButton33.isChecked())
            symptom+=16;
        if (binding.radioButton34.isChecked())
            symptom+=32;
        if (binding.radioButton35.isChecked())
            symptom+=64;
        if (binding.radioButton36.isChecked())
            symptom+=128;
        if (binding.radioButton37.isChecked())
            symptom+=256;
        if (binding.radioButton38.isChecked())
            symptom+=512;
        if (binding.radioButton39.isChecked())
            symptom+=1024;
        if (StringUtils.isNotNull(binding.editTextTextPersonName3.getText().toString())){
            symptom+=2048;
            setMap("Symptom",binding.editTextTextPersonName3.getText().toString());
        }


        return String.valueOf(symptom);
    }

    /**
     * 设置other值
     * @param key
     * @param value
     */
    private void setMap(String key, String value) {
        Map<String,Map> keys = new HashMap<>();
        for (Map<String, Object> map : otherJson) {
            String k = map.get("AttrName").toString();
            keys.put(k,map);
        }
        if (keys.keySet().contains(key)){
            Map map = keys.get(key);
            map.put("OtherText",value);
        }else {
            Map map = new HashMap();
            map.put("AttrName",key);
            map.put("OtherText",value);
            otherJson.add(map);
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        Bundle arguments = getArguments();

        if (arguments == null){
            tbFirstFollowDTO = new TbFirstFollowDTO();
            otherJson = new ArrayList<>();
        }else {
            tbFirstFollowDTO = (TbFirstFollowDTO) arguments.get("tbFirstFollowDTO");
            if (StringUtils.isNotNull(tbFirstFollowDTO.getOtherJson())){
                otherJson = GsonUtils.fromJson(tbFirstFollowDTO.getOtherJson(),List.class);
            }else {
                otherJson = new ArrayList<>();
            }
            inhabitantDTO = viewModel.getInhabitantRepository().findByField("ID", tbFirstFollowDTO.getPatientId());
            if (inhabitantDTO == null){
                Utils.Toast(context,"请先更新病人数据！");
                hideAddFragment();
            }else {
                echo();
            }
        }
    }

    /**
     * 数据回显
     */
    private void echo() {
        //回显病人信息
        setInhabitantView();

        //随访方式
        String wayUp = tbFirstFollowDTO.getWayUp();
        if (StringUtils.isNotNull(wayUp)){
            switch (wayUp){
                case "1":
                    binding.radioGroupPlus01.check(R.id.radioButton50);
                    break;
                case "2":
                    binding.radioGroupPlus01.check(R.id.radioButton49);
                    break;
            }
        }

        //患者类型
        String patientType = tbFirstFollowDTO.getPatientType();
        if (StringUtils.isNotNull(patientType)){
            switch (patientType){
                case "1":
                    binding.radioGroupPlus02.check(R.id.radioButton51);
                    break;
                case "2":
                    binding.radioGroupPlus02.check(R.id.radioButton52);
                    break;
            }
        }

        //痰菌情况
        String sputumType = tbFirstFollowDTO.getSputumType();
        if (StringUtils.isNotNull(sputumType)){
            switch (sputumType){
                case "1":
                    binding.radioGroupPlus03.check(R.id.radioButton53);
                    break;
                case "2":
                    binding.radioGroupPlus03.check(R.id.radioButton54);
                    break;
                case "4":
                    binding.radioGroupPlus03.check(R.id.radioButton55);
                    break;
            }
        }

        //耐药情况
        String drugFastType = tbFirstFollowDTO.getDrugFastType();
        if (StringUtils.isNotNull(drugFastType)){
            switch (drugFastType){
                case "1":
                    binding.radioGroupPlus04.check(R.id.radioButton56);
                    break;
                case "2":
                    binding.radioGroupPlus04.check(R.id.radioButton57);
                    break;
                case "4":
                    binding.radioGroupPlus04.check(R.id.radioButton58);
                    break;
            }
        }

        //症状
        if (StringUtils.isNotNull(tbFirstFollowDTO.getSymptom())
                && !tbFirstFollowDTO.getSymptom().equals("0")){
            List<Integer> list = Utils.divisionBinary(Integer.valueOf(tbFirstFollowDTO.getSymptom()));

            for (Integer integer : list) {
                switch (integer){
                    case 1:
                        binding.radioButton27.setChecked(true);
                        binding.editTextTextPersonName3.setEnabled(false);
                        break;
                    case 2:
                        binding.radioButton28.setChecked(true);
                        break;
                    case 3:
                        binding.radioButton29.setChecked(true);
                        break;
                    case 4:
                        binding.radioButton32.setChecked(true);
                        break;
                    case 5:
                        binding.radioButton33.setChecked(true);
                        break;
                    case 6:
                        binding.radioButton34.setChecked(true);
                        break;
                    case 7:
                        binding.radioButton35.setChecked(true);
                        break;
                    case 8:
                        binding.radioButton36.setChecked(true);
                        break;
                    case 9:
                        binding.radioButton37.setChecked(true);
                        break;
                    case 10:
                        binding.radioButton38.setChecked(true);
                        break;
                    case 11:
                        binding.radioButton39.setChecked(true);
                        break;
                    case 12:
                        if (getMap("Symptom") != null){
                            String symptom = getMap("Symptom");
                            binding.editTextTextPersonName3.setEnabled(true);
                            binding.editTextTextPersonName3.setText(symptom);
                        }
                        break;
                }
            }
        }

        //化疗方案
        if (StringUtils.isNotNull(tbFirstFollowDTO.getChemotherapyRegimen()))
            binding.editTextTextPersonName4.setText(tbFirstFollowDTO.getChemotherapyRegimen());

        //用法
        String usage = tbFirstFollowDTO.getUsage();
        if (StringUtils.isNotNull(usage)){
            switch (usage){
                case "1":
                    binding.radioGroupPlus06.check(R.id.radioButton59);
                    break;
                case "2":
                    binding.radioGroupPlus06.check(R.id.radioButton60);
                    break;
            }
        }

        //药品剂型(1 固定剂量复合制剂，2 散装药，4 板式组合，8注射剂)
        if (StringUtils.isNotNull(tbFirstFollowDTO.getDosage()) && !tbFirstFollowDTO.getDosage().equals("0")){
            List<Integer> list = Utils.divisionBinary(Integer.valueOf(tbFirstFollowDTO.getDosage()));
            for (Integer integer : list) {
                switch (integer){
                    case 1:
                        binding.radioButton61.setChecked(true);
                        break;
                    case 2:
                        binding.radioButton62.setChecked(true);
                        break;
                    case 3:
                        binding.radioButton63.setChecked(true);
                        break;
                    case 4:
                        binding.radioButton64.setChecked(true);
                        break;
                }
            }
        }

        //督导人员选择(1 医生，2 家属，4 自服药，8 其他)
        String supervisor = tbFirstFollowDTO.getSupervisor();
        if (StringUtils.isNotNull(supervisor)){
            switch (supervisor){
                case "1":
                    binding.radioGroupPlus08.check(R.id.radioButton65);
                    break;
                case "2":
                    binding.radioGroupPlus08.check(R.id.radioButton66);
                    break;
                case "4":
                    binding.radioGroupPlus08.check(R.id.radioButton67);
                    break;
                case "8":
                    binding.radioGroupPlus08.check(R.id.radioButton68);
                    break;
            }
        }

        //单独居室
        String alongBedroom = tbFirstFollowDTO.getAlongBedroom();
        if (StringUtils.isNotNull(alongBedroom)){
            switch (alongBedroom){
                case "1":
                    binding.radioGroupPlus09.check(R.id.radioButton69);
                    break;
                case "2":
                    binding.radioGroupPlus09.check(R.id.radioButton70);
                    break;
            }
        }

        //通风情况(1 良好，2 一般，4 差)
        String areationType = tbFirstFollowDTO.getAreationType();
        if (StringUtils.isNotNull(areationType)){
            switch (areationType){
                case "1":
                    binding.radioGroupPlus010.check(R.id.radioButton71);
                    break;
                case "2":
                    binding.radioGroupPlus010.check(R.id.radioButton72);
                    break;
                case "4":
                    binding.radioGroupPlus010.check(R.id.radioButton73);
                    break;
            }
        }

        //日吸烟量
        if (StringUtils.isNotNull(tbFirstFollowDTO.getSmoking()))
            binding.editTextTextPersonName5.setText(tbFirstFollowDTO.getSmoking());

        //日饮酒量
        if (StringUtils.isNotNull(tbFirstFollowDTO.getDailyAlcoholIntake()))
            binding.editTextTextPersonName6.setText(tbFirstFollowDTO.getDailyAlcoholIntake());

        //取药地点
        if (StringUtils.isNotNull(tbFirstFollowDTO.getRecipePlace()))
            binding.editTextTextPersonName7.setText(tbFirstFollowDTO.getRecipePlace());

        //取药时间
        if (StringUtils.isNotNull(tbFirstFollowDTO.getPecipeDate()))
            binding.textView256.setText(tbFirstFollowDTO.getPecipeDate());

        //服药记录卡的填写
        String drugCardFill = tbFirstFollowDTO.getDrugCardFill();
        if (StringUtils.isNotNull(drugCardFill)){
            switch (drugCardFill){
                case "1":
                    binding.radioGroupPlus011.check(R.id.radioButton74);
                    break;
                case "2":
                    binding.radioGroupPlus011.check(R.id.radioButton75);
                    break;
            }
        }

        //服药方法及药品存放
        String drugCardStore = tbFirstFollowDTO.getDrugCardStore();
        if (StringUtils.isNotNull(drugCardStore)){
            switch (drugCardStore){
                case "1":
                    binding.radioGroupPlus012.check(R.id.radioButton76);
                    break;
                case "2":
                    binding.radioGroupPlus012.check(R.id.radioButton77);
                    break;
            }
        }

        //肺结核治疗疗程
        String tbTreatment = tbFirstFollowDTO.getTbTreatment();
        if (StringUtils.isNotNull(tbTreatment)){
            switch (tbTreatment){
                case "1":
                    binding.radioGroupPlus013.check(R.id.radioButton78);
                    break;
                case "2":
                    binding.radioGroupPlus013.check(R.id.radioButton79);
                    break;
            }
        }

        //不规律服药的危害
        String drugHarm = tbFirstFollowDTO.getDrugHarm();
        if (StringUtils.isNotNull(drugHarm)){
            switch (drugHarm){
                case "1":
                    binding.radioGroupPlus014.check(R.id.radioButton80);
                    break;
                case "2":
                    binding.radioGroupPlus014.check(R.id.radioButton81);
                    break;
            }
        }

        //服药后不良反应及处理
        String adverseDrugReactions = tbFirstFollowDTO.getAdverseDrugReactions();
        if (StringUtils.isNotNull(adverseDrugReactions)){
            switch (adverseDrugReactions){
                case "1":
                    binding.radioGroupPlus015.check(R.id.radioButton82);
                    break;
                case "2":
                    binding.radioGroupPlus015.check(R.id.radioButton83);
                    break;
            }
        }

        //治疗期间复诊查痰
        String treatementSputum = tbFirstFollowDTO.getTreatementSputum();
        if (StringUtils.isNotNull(treatementSputum)){
            switch (treatementSputum){
                case "1":
                    binding.radioGroupPlus016.check(R.id.radioButton84);
                    break;
                case "2":
                    binding.radioGroupPlus016.check(R.id.radioButton85);
                    break;
            }
        }

        //外出期间如何坚持服药
        String outdoorMedication = tbFirstFollowDTO.getOutdoorMedication();
        if (StringUtils.isNotNull(outdoorMedication)){
            switch (outdoorMedication){
                case "1":
                    binding.radioGroupPlus017.check(R.id.radioButton86);
                    break;
                case "2":
                    binding.radioGroupPlus017.check(R.id.radioButton87);
                    break;
            }
        }

        //生活习惯及注意事项
        String livingPrecautions = tbFirstFollowDTO.getLivingPrecautions();
        if (StringUtils.isNotNull(livingPrecautions)){
            switch (livingPrecautions){
                case "1":
                    binding.radioGroupPlus018.check(R.id.radioButton88);
                    break;
                case "2":
                    binding.radioGroupPlus018.check(R.id.radioButton89);
                    break;
            }
        }

        //密切接触者检查
        String contactsExam = tbFirstFollowDTO.getContactsExam();
        if (StringUtils.isNotNull(contactsExam)){
            switch (contactsExam){
                case "1":
                    binding.radioGroupPlus019.check(R.id.radioButton90);
                    break;
                case "2":
                    binding.radioGroupPlus019.check(R.id.radioButton91);
                    break;
            }
        }

        //随访时间
        if (StringUtils.isNotNull(tbFirstFollowDTO.getFollowUpDate()))
            binding.textView229.setText(tbFirstFollowDTO.getFollowUpDate());

        //下次随访时间
        if (StringUtils.isNotNull(tbFirstFollowDTO.getNextFollowUpDate()))
            binding.textView231.setText(tbFirstFollowDTO.getNextFollowUpDate());

        //随访医生
        if (StringUtils.isNotNull(tbFirstFollowDTO.getDoctorName()))
            binding.editTextTextPersonName26.setText(tbFirstFollowDTO.getDoctorName());

    }

    private void setInhabitantView(){
        binding.textView177.setText(inhabitantDTO.getNAME());
        if ("1".equals(inhabitantDTO.getSEX()))
            binding.textView179.setText("男");
        else if ("2".equals(inhabitantDTO.getSEX()))
            binding.textView179.setText("女");
        binding.textView183.setText(inhabitantDTO.getTEL());
        binding.textView184.setText(inhabitantDTO.getIDCARD());
    }

    private void clearInhabitantView(){
        binding.textView177.setText("");
        binding.textView179.setText("");
        binding.textView183.setText("");
        binding.textView184.setText("");
        Utils.Toast(context,"未查到该身份证的信息，请同步居民信息后再添加！");
    }


    /**
     * 隐藏或关闭Fragment
     */
    private void hideAddFragment() {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.setCustomAnimations(0, R.anim.fragment_slide_down);
        ft.hide(this);
        ft.commitAllowingStateLoss();
    }


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (buttonView.getId() == binding.radioButton27.getId()){
            if (isChecked){
                binding.editTextTextPersonName3.setEnabled(false);
            }else {
                binding.editTextTextPersonName3.setEnabled(true);
            }
        }
        if (binding.radioButton27.isChecked() && buttonView.getId() != binding.radioButton27.getId()){
            Utils.Toast(context,"请先取消没有症状选项！");
            buttonView.setChecked(false);
            return;
        }
        if (binding.radioButton28.isChecked()
                || binding.radioButton29.isChecked()
                || binding.radioButton32.isChecked()
                || binding.radioButton33.isChecked()
                || binding.radioButton34.isChecked()
                || binding.radioButton35.isChecked()
                || binding.radioButton36.isChecked()
                || binding.radioButton37.isChecked()
                || binding.radioButton38.isChecked()
                || binding.radioButton39.isChecked()){
            if (buttonView.getId() == binding.radioButton27.getId()){
                Utils.Toast(context,"请先取消其他选项！");
                buttonView.setChecked(false);
                return;
            }
        }
    }
    public String getMap(String str){
        for (Map<String, Object> map : otherJson) {
            String attrName = map.get("AttrName").toString();
            String otherText = map.get("OtherText").toString();
            if (attrName.equals(str))
                return otherText;
        }
        return null;
    }
}
